package com.linkallcloud.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XssFilter implements Filter {

    private FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 跨域设置
        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            // 经过在响应 header 中设置 ‘*’ 来容许来自全部域的跨域请求访问。
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            // 经过对 Credentials 参数的设置，就能够保持跨域 Ajax 时的 Cookie
            // 设置了Allow-Credentials，Allow-Origin就不能为*,须要指明具体的url域
            // httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            // 请求方式
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            // （预检请求）的返回结果（即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息） 能够被缓存多久
            httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
            // 首部字段用于预检请求的响应。其指明了实际请求中容许携带的首部字段
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        }
        chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    public FilterConfig getFilterConfig() {
        return filterConfig;
    }

}
